import fetchdata
import json
import tool
import random

def findTranPoint(datalist):
    for one in datalist:
        if "tran_mark" in one:
            del one["tran_mark"]

    span=30
    ruleout=span/10
    for i in xrange(len(datalist)-span):
        exclue=datalist[i:i+ruleout]+datalist[i+span-ruleout:i+span]
        testdata=datalist[i:i+span]
        testdata=sorted(testdata,key=lambda a:a["DI"])
        if testdata[0] not in exclue:
            testdata[0]["tran_mark"]=1
        if testdata[-1] not in exclue:
            testdata[-1]["tran_mark"]=-1

def fetchTranlist(datalist,fun):
    srclist=[]
    reslist=[]
    for one in datalist:
        if "tran_mark" in one:
            srclist.append(fun(one))
            reslist.append(one["tran_mark"])
    return srclist,reslist
def splitTrainTest(inputs,outputs,trainpick=0.7):
    train_output = []
    test_output = []
    train_input = []
    test_input = []
    for i in xrange(len(inputs)):
        if random.random()<trainpick:
            train_input.append(inputs[i])
            train_output.append(outputs[i])
        else:
            test_input.append(inputs[i])
            test_output.append(outputs[i])
    return train_input,train_output,test_input,test_output
if __name__ == "__main__":
    datalist=fetchdata.loaddate("data/golddata.gz")
    findTranPoint(datalist)
    def getone(one):
        return one["macd"][0],one["macd"][1],one["macd"][2],\
        one["sar"]-one["DI"],one["rsi"],one["bband"][0]-one["High"],one["bband"][2]-one["Low"]
    srclist,reslist=fetchTranlist(datalist,getone)
    train_input,train_output,test_input,test_output=splitTrainTest(srclist,reslist)
    fetchdata.savedata(datalist,"data/golddata.gz")
